package com.yegs.jltqc.config;


import com.yegs.jltqc.VO.BaseUser;
import com.yegs.jltqc.dao.BaseUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

@Component
@Order(100)
@WebFilter(filterName = "authenticationFilter",urlPatterns = {"/*"})
public class AuthenticationFilter implements Filter {

    @Autowired
    private BaseUserRepository baseUserRepository;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        if(!url.contains("login")){
            String token = request.getHeader("User-Agent");
            token = request.getHeader("token");
            if(token != null){
                BaseUser user = baseUserRepository.getOne(Long.parseLong(token));
                if(user == null){
                    returnJson(response);
                    return;
                }
                ConcurentCache.setLoginUser(user);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
    /**
     * 返回json，前后端分离
     * @param response
     */
    private void returnJson(HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(Msg.noPermission());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null) {
                writer.close();
            }
        }
    }
}
